package com.xncoding.jwt.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import com.xncoding.jwt.config.WebSocketConfig;

@ServerEndpoint(value = "/websocket", configurator = WebSocketConfig.class)
@Component
public class MyWebSocket {
	// 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	private static AtomicInteger onlineCount = new AtomicInteger(0);

	// concurrent包的线程安全Set，用来存放每个客户端对应的session对象。
	private static ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<String, Session>();

	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(Session session, EndpointConfig config) {

		String username = (String) config.getUserProperties().get("username");
		System.out.println("进入onOpen，用户" + username);
		
//		if(sessions.containsKey(username)) {
//			System.out.println(username+"已登录，请重新登录");
//			session.getAsyncRemote().sendText(username+"已登录，请重新登录");
//		}else {
		
		sessions.put(username, session);

		session.getUserProperties().put("sessionUsername", username);
		int count = onlineCount.incrementAndGet();
		System.out.println("有新连接加入！当前在线人数为" + count);
		session.getAsyncRemote().sendText(count + "");
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session) {
		Map<String, Object> userProperties = session.getUserProperties();
		String username = (String) userProperties.get("sessionUsername");
		sessions.remove(username);
		int count = onlineCount.decrementAndGet();
		System.out.println(session.getUserProperties().get("sessionUsername")+"连接关闭！当前在线人数为" + count);
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message
	 *            客户端发送过来的消息
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		System.out.println(session.getUserProperties().get("sessionUsername")+"来自客户端的消息:" + message);

		Enumeration<String> keys = sessions.keys();
		// 群发消息
		while (keys.hasMoreElements()) {
			String username = keys.nextElement();
			Session session2 = sessions.get(username);
			session2.getAsyncRemote().sendText(message);
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		System.out.println("发生错误");
		error.printStackTrace();
	}

}